package com.h3c.ptability.service;

import com.alibaba.fastjson.JSONObject;
import com.h3c.ptability.client.DataCenterFeignClient;
import com.h3c.ptability.config.mq.LogRabbitConfig;
import com.h3c.ptability.entity.PtNoticeRecord;
import com.h3c.ptability.entity.SdOperLog;
import com.h3c.ptability.mapper.PtNoticeRecordMapper;
import com.h3c.ptability.utils.BusiEnumDefine;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import javax.annotation.Resource;

@Service
public class ManuTranscationService {

    @Autowired
    DataCenterFeignClient dataCenterFeignClient;

    @Resource
    private ValueOperations<String, Object> valueOperations;

    @Autowired
    PtNoticeRecordMapper PtNoticeRecordMapper;

    @Autowired
    private PlatformTransactionManager transactionManager;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private LogRabbitConfig logRabbitConfig;

    public void doSaveInventoryRequestLog(SdOperLog requestLog, boolean options) {
        if (!options) {
            requestLog.setAppId(BusiEnumDefine.PT_LOG_APP_NAME);
            Message message = logRabbitConfig.getMessage(JSONObject.toJSONString(requestLog));
            rabbitTemplate.convertAndSend(logRabbitConfig.getExchange(), logRabbitConfig.getOperLogQueue(), message);
        }
    }

    public void doSaveNoticeRecord(PtNoticeRecord PtNoticeRecord) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);//新发起一个事务
        TransactionStatus status = transactionManager.getTransaction(def);
        try {
            PtNoticeRecordMapper.insertPtNoticeRecord(PtNoticeRecord);

            transactionManager.commit(status);
        } catch (Exception e) {
            transactionManager.rollback(status);
        }

    }

}
